extends TileMap

@onready var astarNode: AStar2D = AStar2D.new()
var mapSize: Vector2i = get_used_rect().size

func _ready():
	var collisionNodes = {}
	# 遍历所有层,将可以寻路的tile加入Astar图的节点中
	for layer in range(get_layers_count()):
		var cells = get_used_cells(layer)
		for cell in cells:
			var tileData = get_cell_tile_data(layer, cell)
			var nodeID = getNodeID(cell)
			var nav = tileData.get_navigation_polygon(0)
			if nav != null:
				astarNode.add_point(nodeID, Vector2(cell.x, cell.y))
			var collision = tileData.get_collision_polygons_count(0)
			if collision > 0:
				collisionNodes[nodeID] = true
	# 移除有碰撞体的点
	# print(mapSize,collisionNodes)
	for nodeID in collisionNodes:
		if astarNode.has_point(nodeID):
			astarNode.remove_point(nodeID)
	# 连接图的节点
	for id in astarNode.get_point_ids():
		var cellPosition = Vector2i(astarNode.get_point_position(id))
		var relativeCells: Array[Vector2i] = [
			cellPosition + Vector2i.RIGHT,
			cellPosition + Vector2i.LEFT,
			cellPosition + Vector2i.DOWN,
			cellPosition + Vector2i.UP,
		]
		for relativeCell in relativeCells:
			var relativeCellIndex = getNodeID(relativeCell)
			if !is_outside_map_bounds(relativeCell) && astarNode.has_point(relativeCellIndex):
				astarNode.connect_points(id, relativeCellIndex, false)

func getNodeID(point: Vector2i) -> int:
	return point.x + point.y * mapSize.x

func is_outside_map_bounds(point: Vector2i) -> bool:
	return point.x < 0 || point.y < 0 || point.x >= mapSize.x || point.y >= mapSize.y

func get_nav_path(startCellPosition: Vector2i, endCellPosition: Vector2i) -> PackedVector2Array:
	var fromID = getNodeID(startCellPosition)
	var toID = getNodeID(endCellPosition)
	var localPath = PackedVector2Array()
	if astarNode.has_point(fromID) && astarNode.has_point(toID):
		var navCellPath = astarNode.get_point_path(fromID, toID)
		# print('navCellPath',navCellPath)
		for cellPosition in navCellPath:
			localPath.push_back(map_to_local(Vector2i(cellPosition)))
	return localPath
